<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-row :gutter="20">
          <!--项目数据-->
          <el-col :span="4" :xs="24">
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入项目名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
              />
            </div>
            <div class="head-container">
              <el-tree
                ref="tree"
                :data="projOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                default-expand-all
                style="font-size: 30px;"
                :render-content="renderContent"
                class="custom-tree-node"
              />
            </div>
          </el-col>
          <!--用户数据-->
          <el-col :span="20" :xs="24">
            <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
              <el-form-item label="候选人名" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入候选人名称"
                  clearable
                  size="small"
                  style="width: 160px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model="queryParams.phone"
                  placeholder="请输入手机号码"
                  clearable
                  size="small"
                  style="width: 160px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <!-- <el-form-item label="状态" prop="status">
                <el-select
                  v-model="queryParams.status"
                  placeholder="用户状态"
                  clearable
                  size="small"
                  style="width: 160px"
                >
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  v-permisaction="['admin:sysUser:add']"
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-permisaction="['admin:sysUser:edit']"
                  type="success"
                  icon="el-icon-edit"
                  size="mini"
                  @click="handleBind"
                >绑定</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-permisaction="['admin:sysUser:remove']"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                >解绑</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-permisaction="['admin:sysUser:add']"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="handleImport"
                >导入</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="loading" :data="htTalentList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" /><el-table-column
                label="姓名"
                align="center"
                prop="name"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-button
                    v-permisaction="['hunter:htTalent:edit']"
                    type="text"
                    size="small"
                    @click="handleUpdate(scope.row)"
                  >{{ scope.row.name }}
                  </el-button>
                </template>

              </el-table-column><el-table-column
                label="手机号"
                align="center"
                prop="phone"
                :show-overflow-tooltip="true"
              /><el-table-column
                label="性别"
                align="center"
                prop="sex"
                :formatter="sexFormat"
                width="100"
              >
                <template slot-scope="scope">
                  {{ sexFormat(scope.row) }}
                </template>
              </el-table-column><el-table-column
                label="评级"
                align="center"
                prop="level"
                :show-overflow-tooltip="true"
              /><el-table-column
                label="备注信息"
                align="center"
                prop="note"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    slot="reference"
                    v-permisaction="['hunter:htTalent:edit']"
                    size="mini"
                    type="text"
                    icon="el-icon-chat-dot-square"
                    @click="handleView(scope.row)"
                  >沟通
                  </el-button>
                  <el-button
                    slot="reference"
                    v-permisaction="['hunter:htTalent:edit']"
                    size="mini"
                    type="text"
                    icon="el-icon-chat-dot-square"
                    @click="handleDelivery(scope.row)"
                  >交付
                  </el-button>
                  <el-popconfirm
                    class="delete-popconfirm"
                    title="确认要修改吗?"
                    confirm-button-text="修改"
                    @confirm="handleUpdate(scope.row)"
                  >
                    <el-button
                      slot="reference"
                      v-permisaction="['hunter:htTalent:edit']"
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                    >修改
                    </el-button>
                  </el-popconfirm>
                  <el-button
                    slot="reference"
                    v-permisaction="['hunter:htTalent:remove']"
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                  >解绑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageIndex"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />

            <!-- 用户导入对话框 -->
            <el-dialog v-if="bindOpen" :title="title" :visible.sync="bindOpen" :width="dialogWidth" :close-on-click-modal="false" @close="cancelBind">
              <talent-select
                ref="talentSelect"
                :project-id="queryParams.projectId"
              />
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitBind">确 定</el-button>
                <el-button @click="cancelBind">取 消</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-row>
      </el-card>
      <!-- 添加或修改参数配置对话框 -->
      <talent-info
        v-if="formOpen || uploadOpen"
        :title="title"
        :form-open="formOpen"
        :from-project="true"
        :upload-open="uploadOpen"
        :proj-options="projOptions"
        :form="form"
        :sex-options="sexOptions"
        :on-close="handleClose"
      />

      <talent-view
        v-if="contractOpen"
        :contract-open="contractOpen"
        :title="title"
        :form="form"
        :sex-options="sexOptions"
        :on-close="handleClose"
      />

      <delivery-info
        v-if="deliverOpen"
        :deliver-open="deliverOpen"
        :title="title"
        :deliver-talent-id="deliverTalentId"
        :on-close="handleClose"
      />
    </template>
  </BasicLayout>

</template>

<script>
import { getHtTalent, listHtTalent } from '@/api/hunter/ht-talent'
import { ShowHtProjectTree, DeleteHtProjectTalent, addHtProjectTalent } from '@/api/hunter/ht-project'
import TalentInfo from '../../components/TalentInfo'
import TalentSelect from '../../components/TalentSelect'
import TalentView from '../../components/TalentView'
import DeliveryInfo from '../../components/DeliverInfo'
export default {
  name: 'HtProjectTalentManager',
  components: { TalentInfo, TalentSelect, TalentView, DeliveryInfo },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 项目树选项
      projOptions: undefined,
      // 是否显示弹出层
      formOpen: false,
      uploadOpen: false,
      bindOpen: false,
      contractOpen: false,
      deliverOpen: false,
      // 部门名称
      deptName: undefined,
      deliverTalentId: undefined,

      htTalentList: [],
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined,
        phone: undefined,
        status: undefined,
        projectId: undefined,
        projectName: undefined,
        note: undefined
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
        projectId: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
        email: [],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogWidth() {
      return window.innerWidth <= 600 ? '90%' : '50%'
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getProjectTree()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
  },
  methods: {
    renderContent(h, { node }) {
      const isSelected = node.data.id === this.queryParams.projectId
      // 如果是选中的ProjectId，则高亮并且显示图标
      return h(
        'span',
        {
          style: {
            display: 'flex',
            alignItems: 'center',
            fontSize: '20px',
            color: isSelected ? '#409EFF' : 'inherit',
            width: '100%' },
          on: {
            click: () => {
              this.handleNodeClick(node.data)
            }
          }
        },
        [
          // h('i', { class: 'el-icon-caret-right', style: { display: isSelected ? 'inline' : 'none' }}), // 添加图标
          node.label
        ]
      )
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      if (this.queryParams.projectId === undefined && this.projOptions.length > 0) {
        this.queryParams.projectId = this.projOptions[0].id
        this.queryParams.projectName = this.projOptions[0].label
        this.form.projectId = this.queryParams.projectId
      }
      if (this.queryParams.projectId === undefined) {
        this.loading = false
        return
      }
      listHtTalent(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.htTalentList = response.data.list
        this.total = response.data.count
        this.loading = false
      }
      )
    },
    /** 查询部门下拉树结构 */
    getProjectTree() {
      ShowHtProjectTree().then(response => {
        this.projOptions = response.data
        this.getList()
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    sexFormat(row) {
      return this.selectDictLabel(this.sexOptions, row.sex)
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.projectId = data.id
      this.queryParams.projectName = data.label
      this.form.projectId = this.queryParams.projectId
      this.getList()
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    handleClose() {
      this.uploadOpen = false
      this.formOpen = false
      this.contractOpen = false
      this.deliverOpen = false
      this.getList()
    },
    cancelBind() {
      this.bindOpen = false
    },
    // 表单重置
    reset() {
      this.form = {
        talentId: undefined,
        projectId: this.queryParams.projectId,
        name: undefined,
        phone: undefined,
        sex: undefined,
        school: undefined,
        company: undefined,
        level: 0,
        status: '2',
        note: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.queryParams.deptId = ''
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.formOpen = true
      this.title = '添加人才'
    },
    handleBind() {
      if (this.queryParams.projectId === undefined) {
        this.msgError('请选择项目')
        return
      }
      this.reset()
      this.bindOpen = true
      this.title = '绑定人才 【 ' + this.queryParams.projectName + ' 】'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const talentId = row.id || this.ids
      getHtTalent(talentId).then(response => {
        this.form = response.data
        this.form.projectId = this.queryParams.projectId
        this.formOpen = true
        this.title = '修改用户'
      })
    },

    submitBind() {
      const talents = this.$refs.talentSelect
      if (talents.selectedTalent.length === 0) {
        this.msgError('至少选择一个人才')
        return
      }
      // 把talents中item的id转换成id列表
      const talentIds = talents.selectedTalent.map(item => item.id)
      addHtProjectTalent({ 'projectId': this.queryParams.projectId, 'Ids': talentIds }).then(response => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.bindOpen = false
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = (row.id && [row.id]) || this.ids
      var that = this
      this.$confirm('是否确认从项目中解除该人才"' + Ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return DeleteHtProjectTalent({ 'projectId': that.queryParams.projectId, 'ids': Ids })
      }).then((response) => {
        if (response.code === 200) {
          that.msgSuccess(response.msg)
          that.getList()
        } else {
          that.msgError(response.msg)
        }
      }).catch(error => {
        // 处理错误信息
        console.error('捕获到错误:', error)
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams
      this.$confirm('是否确认导出所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        // return exportUser(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {})
    },
    /** 导入按钮操作 */
    handleImport() {
      this.title = '用户导入'
      this.uploadOpen = true
    },
    handleView(row) {
      var that = this
      getHtTalent(row.id).then(response => {
        that.reset()
        that.form = response.data
        that.contractOpen = true
        that.title = '沟通人才'
      })
    },
    handleDelivery(row) {
      this.deliverTalentId = row.id
      this.deliverOpen = true
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-tree-node .el-tree-node__content {
  line-height: 40px !important; /* 设置行高 */
  font-size: 25px;
}
.custom-tree-node .el-tree-node{
  margin: 10px 0 !important; /* 增加上下间隔 */
}
</style>
